// -----------------------------------------------------------------------
//  <copyright file="SetFilterGroupsCommand.cs" company="LiuliuSoft">
//      Copyright (c) 2022-2025 DaprPlus. All rights reserved.
//  </copyright>
//  <site>https://dapr.plus</site>
//  <last-editor>郭明锋</last-editor>
//  <last-date>2025/3/15 10:30</last-date>
// -----------------------------------------------------------------------

using DaprPlus.Authorization.Domain;
using DaprPlus.Authorization.Domain.Entities;
using DaprPlus.Authorization.Domain.Specs;
using DaprPlus.Filters;
using DaprPlus.Identity;
using DaprPlus.Specifications;


namespace DaprPlus.Authorization.Application.Commands;

/// <summary>
/// 设置角色资源过滤组命令
/// </summary>
[AuthConfig(typeof(RoleResource), ResourceAccessType.RoleLimit, "SetFilterGroups")]
public class SetFilterGroupsCommand : IRequest<ApiResult>, ICommand
{
    /// <summary>
    /// 资源ID
    /// </summary>
    public long ResourceId { get; set; }

    /// <summary>
    /// 角色ID
    /// </summary>
    public long RoleId { get; set; }

    /// <summary>
    /// 各操作的过滤条件组
    /// </summary>
    public Dictionary<string, FilterGroup> FilterGroups { get; set; } = [];
}

/// <summary>
/// 设置角色资源过滤组命令处理器
/// </summary>
public class SetFilterGroupsCommandHandler(IResourceService service, IRepository<Resource> repository, ILogger<SetFilterGroupsCommandHandler> logger)
    : IRequestHandler<SetFilterGroupsCommand, ApiResult>
{
    public async Task<ApiResult> Handle(SetFilterGroupsCommand request, CancellationToken cancellationToken)
    {
        var resourceId = request.ResourceId;
        var roleId = request.RoleId;
        var filterGroups = request.FilterGroups;

        // 验证资源是否存在
        var spec = new ResourceByIdSpec(resourceId).And(new ResourceIncludeRoleResourceSpec());
        var resource = await repository.GetAsync(spec, cancellationToken);
        if (resource == null)
        {
            return ApiResult.Error($"编号为 {resourceId} 的资源信息不存在");
        }

        // 验证角色资源是否存在
        var roleResource = resource.RoleResources.FirstOrDefault(m => m.RoleId == roleId);
        if (roleResource == null)
        {
            return ApiResult.Error($"角色 {roleId} 的资源权限信息不存在");
        }

        // 设置过滤组
        var result = await service.SetFilterGroupsAsync(resourceId, roleId, filterGroups, cancellationToken);
        logger.LogInformation($"设置角色 {roleId} 的资源 {resourceId} 的过滤组");

        return result;
    }
}

